package model

import (
	"database/sql"
	"gpt-api/framework/db"
	"gpt-api/pkg/util"
)

type Member struct {
	db.BaseModel
	UserID     uint         `json:"user_id" gorm:"column:user_id;type:int;default:0;comment:用户ID"`
	MemberID   uint         `json:"member_id" gorm:"column:member_id;type:int;default:0;comment:所属成员ID"`
	Avatar     string       `json:"avatar" gorm:"column:avatar;type:varchar(255);default:'';comment:头像"`
	Username   string       `json:"username" gorm:"column:username;type:varchar(50);default:'';comment:用户名"`
	Gender     int          `json:"gender" gorm:"column:gender;type:int;default:0;comment:性别0未知，1男，2女"`
	RelationID int          `json:"relation_id" gorm:"column:relation_id;type:int;default:0;comment:关系ID"`
	Birthday   sql.NullTime `json:"birthday" gorm:"column:birthday;type:timestamptz;comment:生日时间"`
	Birthplace string       `json:"birthplace" gorm:"column:birthplace;type:varchar(150);default:'';comment:出生地址"`
	Diedday    sql.NullTime `json:"diedday" gorm:"column:diedday;type:timestamptz;comment:去世时间"`
	Deathplace string       `json:"deathplace" gorm:"column:deathplace;type:varchar(150);default:'';comment:去世地址"`
	Describe   string       `json:"describe" gorm:"column:describe;type:varchar(255);default:'';comment:描述"`
	IsLiving   int          `json:"is_living" gorm:"column:is_living;type:int;default:0;comment:是否在世,0=否，1=是"`
	Relation   Relations    `gorm:"foreignKey:ID;references:RelationID;"`
}

// 定义成员性别常量
type MemberGender int

const (
	MemberGenderUnknown MemberGender = 0 // 未知
	MemberGenderMale    MemberGender = 1 // 男
	MemberGenderFemale  MemberGender = 2 // 女
)

// 根据ID查询成员信息
func (m Member) GetMemberById(database *db.DB, id uint64) (Member, error) {
	var member Member
	err := database.Model(&Member{}).Where("id = ?", id).First(&member).Error
	return member, err
}

// 根据ids查询成员信息
func (m Member) GetMembersByIds(database *db.DB, ids []uint64) ([]Member, error) {
	var member []Member
	err := database.Model(&Member{}).Where("id IN ?", ids).Find(&member).Error
	return member, err
}

// 根据用户ID,成员ID,关系ID获取成员信息
func (m Member) GetMemberForRelationId(database *db.DB, userId uint64, memberId []uint64, ids []uint64) ([]Member, error) {
	var member []Member
	err := database.Model(&Member{}).Where("user_id = ?", userId).Where("member_id IN ?", memberId).Where("relation_id IN ?", ids).Find(&member).Error
	return member, err
}

// 根据MemberId查询下级成员
func (m Member) GetMemberChildren(database *db.DB, id uint64) ([]Member, error) {
	var member []Member
	err := database.Model(&Member{}).Where("member_id = ?", id).Find(&member).Error
	return member, err
}

// 根据UserId查询下级成员
func (m Member) GetMemberChildrenByUserId(database *db.DB, id uint64, member_id ...uint64) ([]Member, error) {
	var member []Member
	init := database.Model(&Member{}).Preload("Relation").Where("user_id = ?", id)
	if len(member_id) > 0 {
		init.Where("member_id = ?", member_id)
	}
	err := init.Order("id ASC").Find(&member).Error
	return member, err
}

// 根据UserId,MemberIds查询下级成员
func (m Member) GetMemberChildrenByUserIdAndMemberIds(database *db.DB, userId uint64, memberIds []uint64) ([]Member, error) {
	var member []Member
	err := database.Model(&Member{}).Preload("Relation").Where("user_id = ?", userId).Where("member_id IN ?", memberIds).Find(&member).Error
	return member, err
}

// 更新OR新增成员信息
func (m Member) AddOrUpdateMember(database *db.DB, member Member) error {
	// 创建事务
	tx := database.Begin()

	// 如果传入ID，则更新
	if member.ID > 0 {
		err := tx.Model(&Member{}).Where("id = ?", member.ID).Save(m).Error
		if err != nil {
			tx.Rollback() // 事务回滚
			return err
		}
	} else {
		err := tx.Create(&m).Error
		if err != nil {
			tx.Rollback() // 事务回滚
			return err
		}
	}

	// 出生日期事件
	if member.Birthday.Valid && member.ID == 0 {
		// 如果是新增成员，同步生成一条默认事件
		birthdayEvent := Events{
			Title:       "出生",
			Content:     member.Birthday.Time.Format("2006-01-02") + " 出生",
			EventTypeID: 1,
			MemberID:    uint(member.ID),
			StartTime:   &member.Birthday.Time,
			UserID:      member.UserID,
		}
		err := tx.Create(&birthdayEvent).Error
		if err != nil {
			tx.Rollback() // 事务回滚
			return err
		}

	}

	// 提交事务
	tx.Commit()
	return nil
}

// 根据用户ID查询根级成员信息
func (m Member) GetMemberRootByUserId(database *db.DB, userId uint64) (Member, error) {
	var member Member
	err := database.Model(&Member{}).Where("user_id = ?", userId).Where("member_id = ?", 0).First(&member).Error
	return member, err
}

// 根据ID删除信息
func (m Member) DeleteMember(database *db.DB, id uint64) error {
	err := database.Model(&Member{}).Where("id = ?", id).Delete(&Member{}).Error
	return err
}

// 递归查询所有兄弟姐妹关系
func (m Member) GetMemberBrothersIdsForDown(database *db.DB, userId uint64, member_id []uint64) ([]uint64, error) {
	var peer_ids []uint64
	peer_ids = append(peer_ids, member_id...)

	// 查询所有成员信息
	allMember, err := m.GetMembersByIds(database, member_id)
	if err != nil {
		return nil, err
	}
	for _, member := range allMember {
		// 如果是兄弟姐妹
		if member.RelationID == 6 || member.RelationID == 7 {
			peer_ids = append(peer_ids, uint64(member.MemberID))
		}
	}

	// 查询下级兄弟姐妹
	peerMember, err := m.GetMemberForRelationId(database, userId, peer_ids, []uint64{6, 7})
	if err != nil {
		return nil, err
	}
	for _, member := range peerMember {
		peer_ids = append(peer_ids, member.ID, uint64(member.MemberID))

		// 数组唯一
		peer_ids = util.ArrayUnique(peer_ids)
		member_id = util.ArrayUnique(member_id)
		if len(peer_ids) == len(member_id) {
			return peer_ids, nil
		}

		// 递归所有兄弟姐妹的兄弟姐妹
		digui, err := m.GetMemberBrothersIdsForDown(database, userId, peer_ids)
		if err != nil {
			return nil, err
		}
		peer_ids = append(peer_ids, digui...)
	}
	return peer_ids, nil
}
